<?php

namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\library\Upload;
use app\common\model\Order;
use app\common\model\OrderComment;
use app\common\model\OrderGoods;
use app\common\model\Shop;
use app\common\model\ShopGoods;
use app\common\resourceHandle\OrderCommentResource;
use function tests\thinkphp\library\think\func_trim;
use think\db\Query;
use think\response\Json;

class OrderCommentLogic extends BaseLogic
{
    public $model;

    public $resourceHandle;

    public function assignModel()
    {
        $this->model          = new OrderComment();
        $this->resourceHandle = new OrderCommentResource();
    }

    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['shop_id'])) {
            $query->where('shop_id', $params['shop_id']);
        }
        if (isset($params['goods_id']) && !empty($params['goods_id'])) {
            $query->where('goods_id', $params['goods_id']);
        }
        if (isset($params['type']) && !empty($params['type'])) {
            $type = (int)$params['type'];
            if ($type === 1) { // 好评
                $between = [4, 5];
            } else if ($type === 2) { // 中评
                $between = [2, 3];
            } else if ($type === 3) { // 差评
                $between = [0, 1];
            }
            if (isset($between)) {
                $query->whereBetween('star', $between);
            }
        }
        return $query;
    }

    /**
     * 订单评价列表
     * @param array $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function index(array $params)
    {
        $params['with'] = ['commentImage', 'member' => function ($query) {
            $query->field(['id', 'member_avatar', 'member_name']);
        }];
        $params['orderBy'] = 'createtime';
        $params['orderType'] = 'desc';
        return $this->getPageList($params)->each(function (&$item){
            $item['service_name'] = OrderGoods::where('order_id',$item['order_id'])->value('goods_name');
            $item['images'] = array_column($item->comment_image->toArray(),'image');
            $item['member_name'] = getCommentName($item['member']['member_name'],$item['anonymous']);
//            $item['member_name'] = star_str($item['member']['member_name']);
            $item['member_avatar'] = $item['member']['member_avatar'];
            unset($item->comment_image,$item['member'],$item['shop_id'],$item['updatetime'],$item['deletetime'],$item['shop_goods_id'],$item['shop_id'],$item['shop_id']);
            return $item;
        });
    }

    /**
     * 评论
     * @param array $params
     * @return string
     * @throws ApiException
     * @throws \app\common\exception\UploadException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function comment(array $params)
    {
        $order = Order::where('member_id', $this->memberId)->with(['orderGoods'])->find($params['order_id']);
        if (empty($order)) throw new ApiException('订单不存在',404);
        if ((int)$order['order_status'] !== Order::ORDER_STATUS_WAIT_COMMENT) throw new ApiException('订单状态错误',404);
        // 评论图片处理
        $commentImage = [];
        if (!empty($params['comment_images'])) {
            if (count($params['comment_images']) > 6) throw new ApiException('图片不能超过6张',404);
            foreach ($params['comment_images'] as $file) {
                $commentImage[] = [
                    'image' => $file
                ];
            }
        }
        //获取店铺商品id
        $shop_goods_id = ShopGoods::where(['goods_id'=>$order['order_goods'][0]['goods_id'],'shop_id'=>$order['shop_id']])->value('id');
        // 保存评论
        $commentData  = [
            'order_id'  => $params['order_id'],
            'member_id' => $this->memberId,
            'shop_id'   => $order['shop_id'],
            'star'      => $params['star'] ?? 5,
            'comment'   => $params['comment'],
            'anonymous' => $params['anonymous'] ?? OrderComment::NOT_ANONYMOUS,
            'shop_goods_id' => $shop_goods_id,
            'goods_id' => $order['order_goods'][0]['goods_id'],
        ];
        $orderComment = $this->getModel()->create($commentData);
        if (!empty($commentImage)) {
            $orderComment->commentImage()->saveAll($commentImage);
        }
        // 修改订单状态
        $order->order_status = Order::ORDER_STATUS_OK;
        $order->save();
        //计算店铺评分
        $satrs = OrderComment::where('shop_id',$order['shop_id'])->sum('star');//获取总评论分数
        $nums = OrderComment::where('shop_id',$order['shop_id'])->count('id');//获取总评论数
        $star = round($satrs/$nums, 2);
        Shop::where('id',$order['shop_id'])->setField('score',$star);
        return true;
    }

    /**
     * 好中差评统计
     * @param array $params
     * @return int[]
     */
    public function commentCount(array $params): array
    {
        if (isset($params['goods_id']) && !empty($params['goods_id'])){
            $list = $this->getModel()->where(['shop_id'=>$params['shop_id'],'goods_id'=>$params['goods_id']])->group('star')->column('star, count(id) as count');
        }else{
            $list = $this->getModel()->where('shop_id', $params['shop_id'])->group('star')->column('star, count(id) as count');
        }
        $res  = [
            ['type'=>0,'name'=>'全部','num'    => 0], // 全部
            ['type'=>1,'name'=>'好评','num'    => 0], // 好评
            ['type'=>2,'name'=>'中评','num'    => 0], // 中评
            ['type'=>3,'name'=>'差评','num'    => 0], // 差评
        ];
        $all = 0;
        foreach ($list as $key => $value) {
            if ($key >= 0 && $key <= 1) {
                $res[3]['num'] += $value;
            } else if ($key >= 2 && $key <= 3) {
                $res[2]['num'] += $value;
            } else if ($key >= 4 && $key <= 5) {
                $res[1]['num'] += $value;
            }
            $all +=$value;
        }
        if ($res[1]['num'] == 0){
            $res[0]['num'] = '0%';
        }else{
            if ($all == 0){
                $res[0]['num'] = '0%';
            }else{
                $res[0]['num'] = '好评率'.(sprintf("%01.2f", $res[1]['num'] / intval($all)) * 100).'%';
            }
        }
        $res[1]['num'] = (string)($res[1]['num']);
        $res[2]['num'] = (string)($res[2]['num']);
        $res[3]['num'] = (string)($res[3]['num']);
        return $res;
    }
}